#!/usr/bin/env python
#       run_debug.py
#       
#       Copyright 2008 Joshua Scotton <josh@joshuascotton.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2008, Joshua Scotton"
__author__ = "Joshua Scotton <josh@joshuascotton.com>"

import os
import string
import ConfigParser

from ConfigParser import ParsingError
from pysqlite2 import dbapi2 as sqlite

class ShowDebug:
    # Video cache database
    VIDEO_DB = os.path.expanduser('~/.entertainer/cache/video.db')
    # Music cache database
    MUSIC_DB = os.path.expanduser('~/.entertainer/cache/music.db')
    # Image cache database
    IMAGE_DB = os.path.expanduser('~/.entertainer/cache/image.db')
    # Feed cache database
    FEED_DB = os.path.expanduser('~/.entertainer/cache/feed.db')
    # Config File
    CONFIG_FILE = os.path.expanduser('~/.entertainer/content.conf')
    
    def __init__(self):
        #initialise config file
        self.config = ConfigParser.ConfigParser()
        try:
            self.config.readfp(open(self.CONFIG_FILE))
        except:
            print "Error with content.conf in FeedConfigToolsTest setUp()"
            sys.exit(1)
    
    def get_feed_list(self):
            feeds = []
            connection = sqlite.connect(self.FEED_DB)
            cursor = connection.cursor()
            cursor.execute("SELECT url FROM feed ORDER BY url")
            for row in cursor:
                feeds.append(row[0])
            connection.close()
            return feeds
    
    def get_feed_list_from_config(self):
        return self.config.get("RSS", "feeds").split(';')
        
    def get_videoclip_list(self):
        connection = sqlite.connect(self.VIDEO_DB)
        cursor = connection.cursor()
        cursor.execute("""SELECT filename
                          FROM   metadata
                          WHERE  type='CLIP'
                          ORDER BY title""")
        clips = []
        for row in cursor:
            clips.append(row[0])
        connection.close()
        return clips
        
    def get_movie_list(self):
        connection = sqlite.connect(self.VIDEO_DB)
        cursor = connection.cursor()
        cursor.execute("""SELECT videofile.filename
                          FROM   videofile, metadata
                          WHERE  type='MOVIE'
                          AND    videofile.filename=metadata.filename
                          ORDER BY title""")
        movies = []
        for row in cursor:
            movies.append(row[0])
        connection.close()
        return movies
        
    def get_episode_list(self):
        connection = sqlite.connect(self.VIDEO_DB)
        cursor = connection.cursor()
        cursor.execute("""SELECT filename
                          FROM   metadata
                          WHERE  type='TV-SERIES'
                          ORDER BY title""")
        episodes = []
        for row in cursor:
            episodes.append(row[0])
        connection.close()
        return episodes
        
    def get_image_list(self):
        connection = sqlite.connect(self.IMAGE_DB)
        cursor = connection.cursor()
        cursor.execute("""SELECT filename
                          FROM   image
                          ORDER BY filename""")
        images = []
        for row in cursor:
            images.append(row[0])
        connection.close()
        return images
        
    def get_album_list(self):
        connection = sqlite.connect(self.MUSIC_DB)
        cursor = connection.cursor()
        cursor.execute("SELECT DISTINCT album FROM track ORDER BY album")
        albums = []
        for row in cursor:
            albums.append(row[0])
        connection.close()
        return albums
        
    def get_track_list(self):
        connection = sqlite.connect(self.MUSIC_DB)
        cursor = connection.cursor()
        cursor.execute("""SELECT filename
                          FROM   track 
                          ORDER BY filename""")
        tracks = []
        for row in cursor:
            tracks.append(row[0])
        connection.close()
        return tracks
        
    def print_list(self, list):
        ret_val = "[\n"
        for item in list:
            ret_val += "\""+str(item)+"\"\n"
        print ret_val + "]"
        
        

    def run_debug(self, verbose=False):
        if not os.path.exists(self.VIDEO_DB):
            raise Exception("Video database doesn't exists!")
        if not os.path.exists(self.MUSIC_DB):
            raise Exception("Music database doesn't exists!")
        if not os.path.exists(self.IMAGE_DB):
            raise Exception("Image database doesn't exists!")
        if not os.path.exists(self.FEED_DB):
            raise Exception("Feed database doesn't exists!")
        
        feeds = self.get_feed_list()
        images = self.get_image_list()
        tracks = self.get_track_list()
        albums = self.get_album_list()
        clips = self.get_videoclip_list()
        movies = self.get_movie_list()
        episodes = self.get_episode_list()
        
        print "### Number of Feeds:        ", len(feeds)
        if verbose:
            self.print_list(feeds)
        if len(feeds) <> len(self.get_feed_list_from_config()):
            print "Number of feeds in db (", len(feeds), ") doesn't match number of feeds in config (", len(self.get_feed_list_from_config()), ")!"
        print "### Number of Images:       ", len(images)
        if verbose:
            self.print_list(images)
        print "### Number of Music Tracks: ", len(tracks)
        if verbose:
            self.print_list(tracks)
        print "### Number of Music Albums: ", len(albums)
        if verbose:
            self.print_list(albums)
        print "### Number of VideoClips:   ", len(clips)
        if verbose:
            self.print_list(clips)
        print "### Number of Movies:       ", len(movies)
        if verbose:
            self.print_list(movies)
        print "### Number of Episodes:     ", len(episodes)
        if verbose:
            self.print_list(episodes)

ShowDebug().run_debug()
